package witJwt

import (
	"github.com/kataras/iris/v12/middleware/jwt"
	"github.com/kataras/iris/v12/x/errors"
	"github.com/spf13/cast"
	"time"
	"wit-admin-go/system/app/model"
	log "wit-admin-go/system/zaplogger"
)

var SigKey = []byte("signature_hmac_secret_shared_key")

type PlayLoad struct {
	Id       string `json:"id"`
	UserName string `json:"userName"`
	Password string `json:"password"`
	jwt.Claims
}

func GenerateToken(user model.User) string {
	// 生效时间
	nowTime := time.Now()
	// 过期时间
	endTime := nowTime.Add(12 * time.Hour)
	// 签名
	signer := jwt.NewSigner(jwt.HS256, SigKey, 12*time.Hour)
	claims := PlayLoad{
		Id:       user.Id,
		UserName: user.UserName,
		Password: user.Password,
		Claims: jwt.Claims{
			Expiry: endTime.Unix(),
			Issuer: "IrisWitAdmin",
		}}
	token, err := signer.Sign(claims)
	if err != nil {
		log.Log.Error(cast.ToString(err))
	}
	s := cast.ToString(token)
	return s
}

// ParseToken 验证Token
func ParseToken(token string) (claims PlayLoad, err error) {
	// token验证
	verifiedToken, err := jwt.Verify(jwt.HS256, SigKey, []byte(token))
	if err != nil {
		return PlayLoad{}, errors.New("登录验证失败，请重新登录！")
	}
	// 获取token中的数据
	_ = verifiedToken.Claims(&claims)
	//fmt.Println("Claims:", claims)
	//log.Infof("Standard Claims:", verifiedToken.StandardClaims)
	return claims, nil
}
